package com.life.smile.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import com.life.smile.entity.RCManagerUser;
import com.life.smile.entity.RearMenu;
import com.life.smile.service.RcUserService;
import com.life.smile.utils.MD5Util;
import com.life.smile.utils.ValidateImage;

@Controller
@RequestMapping("user")
public class RcUserController {

	@Autowired
	private RcUserService rcUserService;
	//HttpServletRequest request;
	//HttpSession session = request.getSession();//session的获取
	
	@ResponseBody
	@RequestMapping(value = "val",method=RequestMethod.POST)
	public String val(HttpServletRequest request,HttpServletResponse response, RCManagerUser user){
		user.setPassword(MD5Util.md5Encode(user.getPassword()));
		RCManagerUser user1 = rcUserService.login(user);
		String code = request.getSession().getAttribute("code").toString();
		String msg = "";
		if(!user.getValCode().equalsIgnoreCase(code)){
			msg = "验证码输入错误";
		}else{			
			if(user1==null){
				msg = "用户名或密码错误";
			}
			else{
				msg = "sucess";
				request.getSession().setAttribute("loginer", user1);
			}
		}
		return msg;
	}
	
	//用户登录并获取相应菜单
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "login",method=RequestMethod.POST)
	public ModelAndView login(HttpServletRequest request,HttpServletResponse response, RCManagerUser user,ModelAndView m,String random_form) {
		//取出session范围内的随机数，对比。
		if(random_form.equals(request.getSession().getAttribute("random_session"))){
			RCManagerUser user1 = (RCManagerUser) request.getSession().getAttribute("loginer");
			List<RearMenu> list = rcUserService.getMenuListByUid(user1.getUserType());//通过用户的角色类型加载相应的菜单
			String role = rcUserService.getRoleNameByUserType(user1.getUserType());//通过用户类型查询对应角色名称
			//创建一个父菜单集合
			List<Map> f_list = new ArrayList<Map>();
			for(int i =0;i<list.size();i++){
				Map f_map = (Map)JSON.toJSON(list.get(i));
				if(f_map.get("level").toString().equals("2")){
					f_list.add(f_map);
				}
			}
			for(Map f_map : f_list){
				List c_list = new ArrayList();
				for(int i=0;i<list.size();i++){
					Map c_map = (Map)JSON.toJSON(list.get(i));
					if(c_map.get("parentid").toString().equals(f_map.get("mid").toString())){
						c_list.add(c_map);
					}
					f_map.put("c_list", c_list);
				}
			}
			m.addObject("role", role);//用户角色
			m.addObject("menu", f_list);//菜单
			m.addObject("loginer", user1);//登录用户信息
			m.setViewName("index");
			addLoginLog(user1,request);//添加日志
			return m;
		}
		m.setViewName("/login");
		return m;
		
	}

	
	@RequestMapping(value = "loginOut",method=RequestMethod.GET)
	public String loginOut (HttpServletRequest request,HttpServletResponse response) {
		request.getSession().removeAttribute("loginer");
		return "/login";
	}
	
	@RequestMapping(value="code")
	public void code(HttpServletResponse response,HttpSession session){
		try {
			ValidateImage img = new ValidateImage(150, 40, 4, 30);
			session.setAttribute("code", img.getRandomCode().toString());
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/jpeg");
			
			ServletOutputStream sos = response.getOutputStream();//获取输出流
			
			ImageIO.write(img.getImage(), "jpeg", sos);//图片流的输出
			
			sos.close();//关闭流
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	/**
	 * 添加登录日志
	 * @param user 登录的用户
	 * @param request
	 * @param type 0登出 1登录
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void addLoginLog(RCManagerUser user,HttpServletRequest request){
		Map pmap = new HashMap();
		pmap.put("userId", user.getUserId());//用户id
		pmap.put("loginTime", new Date());//登录时间
		pmap.put("loginIp", getRemoteIp(request));//用户登录ip
		rcUserService.addLoginLog(pmap);
	}
	/**
     * 获取远程访问IP
     * @return
     */
    protected String getRemoteIp(HttpServletRequest request){
    	String  remoteIp = request.getHeader("x-forwarded-for");
        if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
            remoteIp= request.getHeader("X-Real-IP");
        }
        if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
            remoteIp= request.getHeader("Proxy-Client-IP");
        }
        if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
            remoteIp= request.getHeader("WL-Proxy-Client-IP");
        }
        if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
            remoteIp= request.getHeader("HTTP_CLIENT_IP");
        }
        if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
            remoteIp= request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
            remoteIp= request.getRemoteAddr();
        }
        if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
            remoteIp= request.getRemoteHost();
        }
        return remoteIp;
    }
	

}
